package com.example.intermediatecontrols;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.example.intermediatecontrols.ViewUtils.ViewUtils;

public class EditTextActivity extends AppCompatActivity implements View.OnFocusChangeListener {

    private EditText et_username;

    @SuppressLint("MissingInflatedId")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_edit_text);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });
        EditText et_pwd = findViewById(R.id.et_pwd);
        et_username = findViewById(R.id.et_username);
        et_pwd.setOnFocusChangeListener(this);
        et_username.addTextChangedListener(new MyTextWatcher(et_username, 11));
        et_pwd.addTextChangedListener(new MyTextWatcher(et_username, 6));
    }

    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        if (hasFocus) {
            String userName = et_username.getText().toString();
            if (TextUtils.isEmpty(userName) || userName.length() < 11) {
                et_username.requestFocus();
                Toast.makeText(this, "请输入11位用户名", Toast.LENGTH_SHORT).show();
            }
        }
    }

    class MyTextWatcher implements TextWatcher {
        EditText et;
        int maxLength;

        public MyTextWatcher(EditText et, int maxLength) {
            this.et = et;
            this.maxLength = maxLength;
        }

        @Override
        public void afterTextChanged(Editable s) {
            if (s.toString().length() >= maxLength) {
                ViewUtils.hideKeyBoard(EditTextActivity.this, et);
            }
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }
    }
}